const mysql = require("mysql2/promise");
require("dotenv").config();
const config = require("./db.config.js");
const { Console } = require("winston/lib/winston/transports/index.js");

let pool;
let isInitialized = false;

module.exports = {
  async init() {
    if (isInitialized) return;
    
    try {
      pool = mysql.createPool({
        host: process.env.DB_HOST || config.host,
        user: process.env.DB_USER || config.user,
        password: process.env.DB_PASSWORD || config.password,
        database: process.env.DB_NAME || config.database,
        waitForConnections: true,
        connectionLimit: 10,
        queueLimit: 0,
        connectTimeout: 10000 // 10秒连接超时
      });
      
      // 测试连接
      const conn = await pool.getConnection();
      await conn.query("SELECT 1");
      conn.release();
      
      isInitialized = true;
    } catch (err) {
      console.error("数据库连接池初始化失败:", err);
      throw err;
    }
  },

  async getConnection() {
    if (!isInitialized) {
      await this.init();
    }
    
    try {
      const conn = await pool.getConnection();
      return conn;
    } catch (err) {
      console.error("获取数据库连接失败:", err);
      throw err;
    }
  },
  async execute(sql, params) {
    console.log("执行SQL语句:", sql, params);
    const connection = await this.getConnection();
    try {
      const result = await connection.query(sql, params);
      const [rows] = result; // 再解构一次，取出rows
      return rows||null;
    } finally {
      connection.release();
      // --console.log("数据库连接已释放");
    }
  },
  async query(sql, params) {
    const connection = await this.getConnection();
    try {
      const [rows] = await connection.query(sql, params);
     //--console.log("SQL查询成功:", rows)
      return rows;
    } finally {
      connection.release();
      // --console.log("数据库连接已释放");
    }
  },

  async close() {
    if (pool && isInitialized) {
      await pool.end();
      isInitialized = false;
      // --console.log("数据库连接池已关闭");
    }
  },
  
  isInitialized() {
    return isInitialized;
  }
};